package com.hxl.tech.gateway.auth.dao;


import cn.hutool.core.util.BooleanUtil;
import com.hxl.tech.gateway.auth.dto.limitrule.LimitRuleFindDTO;
import com.hxl.tech.gateway.auth.model.LimitRule;
import com.hxl.tech.gateway.auth.model.QLimitRule;
import com.hxl.tech.gateway.auth.util.QueryDslOrderUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Repository
public class LimitRuleDao {

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    private QLimitRule qLimitRule = QLimitRule.limitRule;

    public List<LimitRule> find(LimitRuleFindDTO findDTO, Boolean page) {

        JPAQuery<LimitRule> query = jpaQueryFactory.select(qLimitRule).from(qLimitRule);
        query.where(booleanBuilder(findDTO));

        if (Objects.nonNull(findDTO.getProperty()) && Objects.nonNull(findDTO.getDirection())) {
            OrderSpecifier orderSpecifier = QueryDslOrderUtil.orderByField(qLimitRule, findDTO.getDirection(), findDTO.getProperty());
            query.orderBy(orderSpecifier);
        } else {
            query.orderBy(qLimitRule.createTime.desc());
        }

        return BooleanUtil.isTrue(page) ? query.limit(findDTO.limit()).offset(findDTO.offset()).fetch() : query.fetch();
    }

    public Long count(LimitRuleFindDTO findDTO) {

        JPAQuery<String> query = jpaQueryFactory.select(qLimitRule.ruleId).from(qLimitRule);
        query.where(booleanBuilder(findDTO));
        return Long.valueOf(query.fetch().size());
    }

    public BooleanBuilder booleanBuilder(LimitRuleFindDTO findDTO) {

        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotEmpty(findDTO.getAppId())) {
            builder.and(qLimitRule.appId.eq(findDTO.getAppId()));
        }
        if (StringUtils.isNotEmpty(findDTO.getMerchantCode())) {
            builder.and(qLimitRule.merchantCode.eq(findDTO.getMerchantCode()));
        }
        if (StringUtils.isNotEmpty(findDTO.getApiName())) {
            builder.and(qLimitRule.apiName.eq(findDTO.getApiName()));
        }
        if (StringUtils.isNotEmpty(findDTO.getRuleName())) {
            builder.and(qLimitRule.ruleName.like("%" + findDTO.getRuleName() + "%"));
        }

        return builder;
    }

    public LimitRule read(String ruleId) {

        JPAQuery<LimitRule> query = jpaQueryFactory.select(qLimitRule)
                .from(qLimitRule)
                .where(qLimitRule.ruleId.eq(ruleId));
        return query.fetchOne();
    }

    public List<LimitRule> findAll() {

        JPAQuery<LimitRule> query = jpaQueryFactory.select(qLimitRule).from(qLimitRule);
        return query.fetch();
    }
}
